package com.iyue;

import java.io.IOException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.iyue.core.pojo.UserAccount;
import com.iyue.framework.BaseAction;
import com.iyue.framework.cache.IMemcachedCache;
import com.iyue.servlet.taglibs.Functions;
import com.iyue.sso.bean.SSOInfo;
import com.iyue.sso.helper.SSOUtil;
import com.iyue.user.helper.UserFunctions;
import com.iyue.user.pojo.UserBasic;
import com.iyue.user.service.UserBiz;
import com.iyue.util.Mobile;

/**
 * 《网站》实用类
 * 
 * @author 孙晓晔
 * @version $Id: Util.java,v 1.2 2011/01/05 09:35:29 fresh Exp $
 */
public abstract class Util {

	protected static final Logger logger = Logger.getLogger(Util.class);

	/**
	 * 黑名单
	 */
	public final static Integer IS_BLACK = 0;
	/**
	 * 自己
	 */
	public final static Integer IS_SELF = 1;
	/**
	 * 粉丝
	 */
	public final static Integer IS_Followed = 2;
	/**
	 * 访客
	 */
	public final static Integer IS_GUEST = 3;

	/**
	 * 基于session实现的防刷检查方法，默认有效时长10秒。
	 * 
	 * @param request
	 * @param key
	 * @param duration
	 *            有效时长,单位毫秒
	 * @return 存在有效key返回true, 否则返回false
	 */
	public static boolean check(HttpServletRequest request, String key,
			Integer duration) {
		if (duration == null) {
			duration = 5000;
		}

		long currentTimeMillis = System.currentTimeMillis();
		Long last = Long.valueOf(currentTimeMillis);

		HttpSession session = request.getSession();
		Long time = (Long) session.getAttribute(key);
		if (time == null || currentTimeMillis - time.longValue() > duration) {
			session.setAttribute(key, last);
			return false;
		}

		return true;
	}

	/**
	 * 登录
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @param action
	 * @return page
	 * @throws Exception
	 */
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		String mobile = Mobile.cmcc(request);
		String uri = "portal.do?do=Portal.my";
		if (Mobile.isCmcc(mobile)) {
			StringBuffer sb = new StringBuffer();
			sb.append(request.getScheme());
			sb.append("://");
			sb.append(request.getServerName());
			if (request.getServerPort() != 80) {
				sb.append(":");
				sb.append(request.getServerPort());
			}
			sb.append(request.getContextPath());

			String location = sb.toString() + uri;
			request.setAttribute("login_url", location);

			return action.display(request, response, "login_auto");
		}

		return action.display(request, response, "login");
	}

	/**
	 * 获取用户帐号
	 * 
	 * @param request
	 *            请求
	 * @return String
	 */
	public Integer username(HttpServletRequest request) {
		String uid = request.getParameter("uid");
		if (StringUtils.isBlank(uid)) {
			SSOInfo info = SSOUtil.getSSO(request);
			if (info == null) {
				return null;
			}

			if (!info.getValid()) {
				return null;
			}

			Integer username = info.getUsername();
			if (username != null) {
				uid = username.toString();
			}

			request.setAttribute("userId", info.getUsername());
		}

		if (StringUtils.isBlank(uid)) {
			return null;
		}

		request.setAttribute("uid", uid);

		return new Integer(uid);
	}

	/**
	 * 通过会话获取用户
	 * 
	 * @param request
	 * @return
	 */
	public UserBasic user(HttpServletRequest request) {
		Integer username = u(request);
		if (username == null) {
			return null;
		}

		UserBasic user = UserFunctions.user(username.toString());
		if (user == null) {
			return null;
		}

		return user;
	}

	/**
	 * 通过会话获取用户
	 * 
	 * @param request
	 * @return
	 */
	public static Integer u(HttpServletRequest request) {
		Integer ret = (Integer) request.getAttribute("userId");
		if (ret != null) {
			request.setAttribute("userId", ret);
			return ret;
		}

		SSOInfo info = SSOUtil.getSSO(request);
		if (info == null) {
			return null;
		}

		if (!info.getValid()) {
			return null;
		}

		ret = info.getUsername();
		if (ret == null || ret.equals(0)) {
			return null;
		}

		request.setAttribute("userId", ret);

		return ret;
	}


	/**
	 * 生成用户帐号信息
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public UserAccount account(String account, String password) {
		if (password == null || "".equals(password)) {
			password = login_code();
		}

		int max = 10, i = 0;
		for (; i < max; i++) {
			if (!(checkPasswd(password) > UserAccount.PASSWORD_REGULAR)) {
				break;
			} else {
				password = login_code();
			}
		}

		if (i == max) {
			password = "m8b5z3";
		}

		UserAccount user = new UserAccount();
		user.setAccount(account);
		user.setPassword(password);
		user.setStatus(UserAccount.STATUS_OK);

		return user;
	}

	public static int checkPasswd(String passwd) {
		if (passwd == null || passwd.length() == 0) {
			return UserAccount.PASSWORD_NULL;
		}
		if (passwd.length() < 6) {
			return UserAccount.PASSWORD_LENGTH;
		}
		if (isSimple(passwd)) {
			return UserAccount.PASSWORD_SIMPLE;
		}

		return UserAccount.PASSWORD_REGULAR;
	}

	private static boolean isSimple(String passwd) {
		if (passwd == null) {
			return true;
		}

		if (sameCode(passwd, 3)) {
			return true;
		}

		return Pattern.matches("[a-zA-Z]?12345(6(7(8(9)?)?)?)?", passwd)
				|| Pattern.matches("[a-zA-Z]?((((9)?8)?7)?6)?54321", passwd);
	}

	/**
	 * max个以上不同字符
	 * 
	 * @param passwd
	 * @param max
	 * @return
	 */
	private static boolean sameCode(String passwd, int max) {
		if (passwd == null) {
			return true;
		}

		byte[] bytes = passwd.getBytes();
		byte[][] count = new byte[2][bytes.length + 1];
		int i = 0;
		int imax = -1;
		for (byte b : bytes) {
			i = 0;
			while (i <= imax && count[0][i] != b) {
				i++;
			}
			count[0][i] = b;
			if ((i + 1) >= max) {
				return false;
			}
			imax = i > imax ? i : imax;
		}

		return true;
	}

	/**
	 * 产生随机数
	 * 
	 * @return String
	 */
	public String login_code() {
		String[] number = new String[] { "a", "c", "d", "e", "f", "h", "n",
				"m", "k", "y", "w", "t", "2", "3", "4", "5", "7", "8" };

		Random rnd = new Random();
		int p = number.length - 1;

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int j = rnd.nextInt(p) + 1;
			sb.append(number[j]);
		}

		return sb.toString();
	}

	/**
	 * 产生随机数
	 * 
	 * @return String
	 */
	public String vcode() {
		String[] number = new String[] { "2", "3", "4", "5", "6", "7", "8" };

		Random rnd = new Random();
		int p = number.length - 1;

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			int j = rnd.nextInt(p) + 1;
			sb.append(number[j]);
		}

		return sb.toString();
	}

	public String login_code(int s) {
		String[] number = new String[] { "2", "3", "4", "5", "6", "7", "8" };

		Random rnd = new Random();
		int p = number.length - 1;

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s; i++) {
			int j = rnd.nextInt(p) + 1;
			sb.append(number[j]);
		}

		return sb.toString();
	}

	/**
	 * 产生随机数
	 * 
	 * @param mobile
	 *            手机号码
	 * @return
	 */
	public String login_vcode(String mobile) {
		String vcode = login_code();

		IMemcachedCache cache = (IMemcachedCache) SpringHelper
				.getBean("FastMemcachedCache");
		String key = Functions.KEY_PASSWORD_VCODE + mobile;
		cache.add(key, vcode, Functions.MINUTE * 5);

		return vcode;
	}

	/**
	 * 验证码核对
	 * 
	 * @param mobile
	 *            手机号码
	 * @param vcode
	 *            验证码
	 * @return
	 */
	public boolean login_vcode(String mobile, String vcode) {
		if (vcode == null || vcode.equals("")) {
			return false;
		}

		if (mobile == null || mobile.equals("")) {
			return false;
		}
		if (Mobile.isCmcc(mobile)) {
			IMemcachedCache cache = (IMemcachedCache) SpringHelper
					.getBean("FastMemcachedCache");
			String key = Functions.KEY_PASSWORD_VCODE + mobile;
			Object obj = cache.get(key);
			if (obj != null) {
				if (obj instanceof String) {
					String code = (String) obj;
					if (vcode.equals(code)) {
						return true;
					}
				} else {
					cache.delete(key);
				}
			}
		}

		return false;
	}

	/**
	 * 
	 * 
	 * @param request
	 * @return String
	 */
	protected String get(HttpServletRequest request, String key) {
		HttpSession session = request.getSession();

		String s = request.getParameter(key);
		if (s != null && s.length() > 0) {
			request.setAttribute(key, s);
			session.setAttribute(key, s);
			return s;
		}

		s = (String) session.getAttribute(key);
		if (s != null && s.length() > 0) {
			request.setAttribute(key, s);
			return s;
		}

		return null;
	}

	/**
	 * 判断是否登录
	 * 
	 * @param request
	 * @return
	 */
	public boolean isLogin(HttpServletRequest request) {
		SSOInfo info = SSOUtil.getSSO(request);
		if (info == null) {
			return false;
		}

		if (!info.getValid()) {
			return false;
		}

		request.setAttribute("userId", info.getUsername());

		return true;
	}

	/**
	 * 页面跳转--如果url为空跳转到首页
	 * 
	 * @param request
	 * @param response
	 * @param url
	 * @throws IOException
	 */
	protected void Redirect(HttpServletRequest request,
			HttpServletResponse response, String url) throws IOException {
		if (url == null || url.length() < 3) {
			String vf = SSOUtil.getVf(request);
			if (StringUtils.isBlank(vf)) {
				vf = "";
			}

			url = "/portal.do?do=Portal.my&vf=" + vf;
		}

		if (url.indexOf("vf") > 0) {
			url = url.replace("&amp;", "&");
			response.sendRedirect(url);
			return;
		}

		if (url.startsWith("http://")) {
			url = url.replace("&amp;", "&");
			response.sendRedirect(url);
			return;
		}

		String vf = SSOUtil.getVf(request);
		if (StringUtils.isBlank(vf)) {
			vf = "";
		}

		response.sendRedirect(url);
	}

	/**
	 * 信息提示
	 * 
	 * @param request
	 * @param response
	 * @param action
	 * @return page
	 * @throws Exception
	 */
	protected ActionForward info(HttpServletRequest request,
			HttpServletResponse response, BaseAction action) throws Exception {

		String go = request.getParameter("go");
		if (go != null && go.length() > 3) {
			go = go.replace("&", "&amp;");
			go = go.replace("&amp;&amp;", "&amp;");
			request.setAttribute("backLink", go);
		}

		return action.display(request, response, "info");
	}

	/**
	 * 提示信息
	 * 
	 * @param msg
	 *            类别
	 * @param ss
	 *            内容
	 * @return String
	 */
	protected String msg(Integer msg, String[] ss) {
		Config cfg = (Config) SpringHelper.getBean("config");
		Map<String, String> messages = cfg.getMessages();

		String pattern = messages.get(msg.toString());
		if (pattern == null) {
			return "";
		}

		MessageFormat mf = new MessageFormat(pattern);

		return mf.format(ss).trim();
	}

	/**
	 * 返回
	 * 
	 * @param request
	 *            请求
	 * @param pattern
	 *            样式
	 * @return
	 */
	protected void back(HttpServletRequest request, String pattern) {

		String p1 = (String) request.getAttribute("p1");
		if (StringUtils.isBlank(p1)) {
			p1 = "?";
		}
		// pattern = pattern.replace("?", "&amp;");
		// String js = (String) request.getAttribute("js");
		// String[] ss = new String[] { js };

		MessageFormat mf = new MessageFormat(pattern);
		String[] ss = new String[] { p1 };
		request.setAttribute("backLink", mf.format(ss));
	}

	/*
	 * 确认删除
	 */
	public ActionForward confirm(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			BaseAction action) throws Exception {
		if (!isLogin(request)) {
			return action.display(request, response, "login");
		}
		String url = null;
		String pdo = "";
		String tid = request.getParameter("tid");
		String fid = request.getParameter("fid");
		String gid = request.getParameter("gid");
		String uid = request.getParameter("uid");
		String ss = request.getParameter("confirm");
		if (ss.equals("forum")) {
			url = "forum.do";
			pdo = "Text.delete&amp;tid=" + tid + "&amp;fid=" + fid;
		}

		if (ss.equals("photo")) {
			url = "photo.do";
			pdo = "Text.delete&amp;tid=" + tid + "&amp;uid=" + uid;
		}

		if (ss.equals("friend_group")) {
			url = "friend.do";
			pdo = "Group.delete&amp;gid=" + gid;
		}

		request.setAttribute("url", url);
		request.setAttribute("do", pdo);

		return action.display(request, response, "confirm");
	}

	/**
	 * 处理删除图片
	 * 
	 * @param path
	 */
	public void delete_image(String path) {
		if (path == null || path.length() <= 0) {
			return;
		}

		int isFile = path.indexOf("getfile/");
		if (isFile <= 0) {
			return;
		}

		HttpClient http = new HttpClient();
		HttpClientParams params = http.getParams();
		params.setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
		params.setParameter("http.socket.timeout", new Integer(5000));
		params.setParameter("http.protocol.content-charset", "UTF-8");

		Config cfg = (Config) SpringHelper.getBean("test");
		String url = cfg.getFile() + "/delfile/" + path.substring(isFile + 8);
		GetMethod method = new GetMethod(url);
		method.setRequestHeader("User-Agent", "test");
		method.setRequestHeader("Connection", "close");
		try {
			http.executeMethod(method);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 判断时间在100年之内
	 * 
	 * @param time
	 * @return
	 */
	@SuppressWarnings("static-access")
	public Date date(String time, String format) {
		if (time == null || "".equals(time)) {
			return null;
		}

		if (format == null || "".equals(format)) {
			format = "yyyyMMdd";
		}

		if (!time.matches("[\\d]{" + format.length() + "}")) {
			return null;
		}

		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Calendar today = Calendar.getInstance();
		Date start = null;
		try {
			start = sdf.parse(time);
		} catch (Exception ex) {
			start = today.getTime();
		}

		Calendar before = Calendar.getInstance();
		before.setTime(start);

		if (today.get(today.YEAR) - before.get(before.YEAR) >= 100) {
			return null;
		}

		if (before.after(today)) {
			return null;
		}

		if (format.equals("yyyyMMdd")) {
			if (sdf.format(today.getTime()).equals(time)) {
				return null;
			}
		}

		return start;
	}

	public String trim_msg(String forward) {
		int idx = forward.indexOf("&msg");
		if (idx != -1) {
			forward = forward.substring(0, idx);
		}
		return forward;
	}

	/**
	 * 保存头像
	 * 
	 * @param username
	 * @param url
	 * @return
	 */
	protected int save_user_photo(Integer username, String url) {
		if (username == null || url == null || url.length() < 3) {
			return -1;
		}

		UserBiz biz = (UserBiz) SpringHelper.getBean("UserBiz");
		int ret = 0;
		UserBasic basic = biz.basic(username);
		if (basic == null) {
			basic = new UserBasic();
			basic.setUsername(username);
			basic.setPhoto(url);
			ret = biz.save_basic(basic);
		} else {
			basic.setPhoto(url);
			ret = biz.update_photo(username, url);
		}

		return ret;
	}

	/**
	 * 格式化状态保持参数
	 * 
	 * @param request
	 * @param url
	 * @return
	 */
	public static String url(HttpServletRequest request, String page,
			String param) {

		String p1 = (String) request.getAttribute("p1");

		if (p1 == null) {
			p1 = "?1=";
		} else {
			p1 = p1.replace("&amp;", "&");
		}
		if (page.indexOf("?") > 0) {
			p1 = p1.replaceFirst("\\?", "&");
		}

		StringBuffer ret = new StringBuffer(page);
		ret.append(p1);
		if (param != null && param.length() > 0) {
			ret.append("&");
			ret.append(param);
		}

		return ret.toString();
	}

}
